<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');    // 0 or 1 set 1 if unable to download database it will show all possible errors
ini_set('max_execution_time', 0);  // setting 0 for no time limit
define('BACKUP_DIR', './bochihuyBackups' ) ;
$username='root';
$password='root';


if(isset($_SESSION["session"]["sUserName"])){
if(isset($_GET['clear'])&& $_GET['clear']=='clear'){
    $file_name=$_GET['file'];
    $file=BACKUP_DIR.DIRECTORY_SEPARATOR.$file_name;
    if(file_exists($file)){ if(unlink($file)) $rmsg="$file_name xóa thành công";}
    else { $rmsg="<b>$file_name </b>Not found already removed";}
}

if(isset($_REQUEST['submit'])){


$fileName = 'bochihuy_backup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ; 

if(function_exists('max_execution_time')) {
if( ini_get('max_execution_time') > 0 ) 	set_time_limit(0) ;
}

// Check if directory is already created and has the proper permissions
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ;
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ; 

// Create an ".htaccess" file , it will restrict direct accss to the backup-directory . 
$content = 'Allow from all' ; 
$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ;
$file->fwrite($content) ;

$mysqli = new mysqli(HOST , DATABASE_USER , DATABASE_PASS , DATABASE_NAME) ;
// $mysqli = new mysqli('172.16.5.4' , 'root' , '12345' , 'bochihuy_new') ;
if (mysqli_connect_errno())
{
   printf("Connect failed: %s", mysqli_connect_error());
   exit();
}
 // Introduction information
$return='';
 $return .= "--\n";
$return .= "-- A Mysql Backup System \n";
$return .= "--\n";
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
$return = "--\n";
$return .= "-- Database : " . DATABASE_NAME . "\n";
$return .= "--\n";
$return .= "-- --------------------------------------------------\n";
$return .= "-- ---------------------------------------------------\n";
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ;
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ;
$tables = array() ; 
// Exploring what tables this database has
$result = $mysqli->query('SHOW TABLES' ) ; 
// Cycle through "$result" and put content into an array
while ($row = $result->fetch_row()) 
{
    $tables[] = $row[0] ;
}
// Cycle through each  table
foreach($tables as $table)
{ 
    // Get content of each table
    $result = $mysqli->query('SELECT * FROM '. $table) ; 
    // Get number of fields (columns) of each table
    $num_fields = $mysqli->field_count  ;
    // Add table information
    $return .= "--\n" ;
    $return .= '-- Tabel structure for table `' . $table . '`' . "\n" ;
    $return .= "--\n" ;
    $return.= 'DROP TABLE  IF EXISTS `'.$table.'`;' . "\n" ; 
    // Get the table-shema
    $shema = $mysqli->query('SHOW CREATE TABLE '.$table) ;
    // Extract table shema 
    $tableshema = $shema->fetch_row() ; 
    // Append table-shema into code
    $return.= $tableshema[1].";" . "\n\n" ; 
    // Cycle through each table-row
    while($rowdata = $result->fetch_row()) 
    { 
        // Prepare code that will insert data into table 
        $return .= 'INSERT INTO `'.$table .'`  VALUES ( '  ;
        // Extract data of each row 
        for($i=0; $i<$num_fields; $i++)
        {   
        $return .= '"'.$mysqli->real_escape_string($rowdata[$i]) . "\"," ;
        }
        // Let's remove the last comma 
        $return = substr("$return", 0, -1) ; 
        $return .= ");" ."\n" ;
    } 
 $return .= "\n\n" ; 
}
// Close the connection
$mysqli->close() ;
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; '  . "\n" ; 
$return .= 'COMMIT ; '  . "\n" ;
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n"  ; 
//$file = file_put_contents($fileName , $return) ; 
$zip = new ZipArchive() ;
$resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ;
if( $resOpen ){
$zip->addFromString( $fileName , "$return" ) ;
    }
$zip->close() ;
$fileSize = get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ; 
// Function to append proper Unit after file-size . 
}

?>
<style type="text/css">
  .buttombackup{
    border: none;
    padding: 15px 5px;
    color: #0B55C4;
    text-align: justify;
    background: url('template/default/images/ico_backup.png');

  }  
.buttombackup:hover{
    border: 1px solid #FBFBFB;
    cursor: pointer;
}
</style>
 <form name="form" method="post" action=""> 
<div id="toolbar-box">

    <div class="d_divide5"></div> 
    <div class="toolbar" id="toolbar"> 
        <table class="toolbar">
            <tbody>
                <tr>
                    <td class="button" id="toolbar-publish">
                         <a href="javascript:history.go(-1)" class="toolbar">
                        <span class="icon-32-back" title="Quay lại"></span>
                            Quay Lại
                    </a>
                    </td>
                    
                    <td class="button" id="toolbar-publish">
                       
                        <input onclick="vky(this)" class="buttombackup" type="submit" id="getdb" name="submit" value="&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp" />
                        <script type="text/javascript">
                        function vky(x){
                            x.value='Wait processing..';
                            document.getElementsByClassName("overlay")[0].style.display="block";
                        }
                        </script>
                    </td>
                   



                </tr>
            </tbody>
        </table>
    </div><!-- end toolbar -->


    <div class="header icon_48_backup">Quản lý sao lưu dữ liệu</div>

    <div class="d_divide5"></div>
</div>

<div class="d_divide10"></div>
<div class="d_clear"></div>


</form>




  
    
    <div id="element-box">
        <div class=""><?php echo isset($rmsg)?$rmsg:''; ?></div>
        <?php echo display_download(BACKUP_DIR); ?>
    </div>   

<?php }
?>

<style type="text/css">
    a.tooltips {  position: relative;  display: inline;}
a.tooltips span {position: absolute;width:140px;color: #000000;background: #FFFFFF;border: 2px solid #CCCCCC;height: 32px;line-height: 32px;text-align: center;visibility: hidden;border-radius: 6px;box-shadow: 0px 0px 7px #808080;}
a.tooltips span:before {content: '';position: absolute;top: 100%;left: 50%;margin-left: -12px;width: 0; height: 0;border-top: 12px solid #CCCCCC;border-right: 12px solid transparent;border-left: 12px solid transparent;}
a.tooltips span:after {content: '';position: absolute;top: 100%;left: 50%;margin-left: -8px;width: 0; height: 0;border-top: 8px solid #FFFFFF;border-right: 8px solid transparent;border-left: 8px solid transparent;}
a:hover.tooltips span {visibility: visible;opacity: 1;bottom: 30px;left: 50%;margin-left: -76px;z-index: 999;}
</style>

<?php 
function get_file_size_unit($file_size){
switch (true) {
    case ($file_size/1024 < 1) :
        return intval($file_size ) ." Bytes" ;
        break;
    case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1)  :
        return intval($file_size/1024) ." KB" ;
        break;
	default:
	return intval($file_size/(1024*1024)) ." MB" ;
}
}
function display_download($BACKUP_DIR){
$msg='';
$msg.='
 <table class="adminlist" cellspacing="1">

 <thead>
                <tr>
                    <th width="20%"><a href="javascript:void(0)">Tên file</a></th>  
                     <th width="10%"><a href="javascript:void(0)">Size</a></th>  
                      <th align="center" width="10%"><a href="#"></a></th>
                    
                </tr>
            </thead>

<tbody>';
$downloads=getDownloads($BACKUP_DIR);
if(count($downloads)>0)
foreach ($downloads as $k => $v) {
$msg.= '<tr><td  align="center">'.$v['name'].'</td><td>'.$v['size'].'</td><td>
<a class="tooltips" href="'.BACKUP_DIR . "/". $v['name'] .'" target="_blank"><span>Download</span><img src=""/></a>
&nbsp;|&nbsp;<a onclick="return confirm(\'Bạn có chắc muốn xóa file này?\')" class="tooltips" href="?com=com_backup&task=view&clear=clear&file='.$v['name'].'"><span>Click to Remove</span><img src=""/></a>
</td></tr>';   
}
return $msg.='</tbody></table>';
}
function getDownloads($dir="./bochihuyBackups"){
    if (is_dir($dir)){
    $dh  = opendir($dir);
    $files=array();
    $i=0;
    $xclude=array('.','..','.htaccess');
    while (false !== ($filename = readdir($dh))) {
       if(!in_array($filename, $xclude))
       {
        $files[$i]['name'] = $filename;
        $files[$i]['size'] = get_file_size_unit(filesize($dir.'/'.$filename));
        $i++;
       }
    }
    return $files;
}}?>